package com.bw.shop;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.bw.common.field.EventBusEntity;
import com.bw.common.utils.ToastShowUtils;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.Map;

@Route(path = "/app/payactivity")
public class PayActivity extends AppCompatActivity {

    private String paySign;
    private PayHandler mHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        paySign = getIntent().getBundleExtra("bundle").getString("paysign");
        mHandler = new PayHandler(this);
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String,String> result = alipay.payV2(paySign,true);
                Message msg = new Message();
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public static class PayHandler extends Handler{
        private WeakReference<PayActivity>weakReference;
        public PayHandler(PayActivity payActivity){
            weakReference = new WeakReference<>(payActivity);
        }
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Map<String,String> result = (Map<String, String>) msg.obj;
            String resultStatus = result.get("resultStatus");
            if (resultStatus.equals("9000")){
                EventBusEntity eventBusEntity = new EventBusEntity();
                eventBusEntity.action = "refreshOrder";
                EventBus.getDefault().post(eventBusEntity);
            }else {
                ToastShowUtils.showShort("支付失败");
            }
            weakReference.get().finish();
        }
    }

}
